package com.ys.erp.stage_mall_service.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.entity.data.bean.User;
import com.ys.erp.entity.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author lwj
 * @date 2023/5/22
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WxSendMessageUtil {

    @Value("${wx.mini-program-state}")
    private String miniProgramState;

    @Value("${wx.subscribeGoodsTemplateId}")
    private String subscribeGoodsTemplateId;

    private final WxUtil wxUtil;

    private final RestTemplate restTemplate;

    private final IUserService iUserService;


    /**
     * 用户订阅商品
     */
    @Async
    public void subscribeGoods(Long userId, String goodsName) {
        try {
            User byId = iUserService.getById(userId);
            if (ObjectUtils.isEmpty(byId)) {
                return;
            }
            JSONObject dataObj = new JSONObject();
            JSONObject value1 = new JSONObject();
            if (goodsName.length() > 20) {
                goodsName = goodsName.substring(0, 19);
            }
            value1.put("value", goodsName);
            dataObj.put("thing2", value1);
            JSONObject value2 = new JSONObject();
            value2.put("value", "您心动的商品已补货，感谢您的耐心等待");
            dataObj.put("thing3", value2);
            sendMessage(byId.getOpenId(), subscribeGoodsTemplateId, "", dataObj);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String openId, String templateId, String page, JSONObject data) {
        String accessToken = wxUtil.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        JSONObject param = new JSONObject();
        param.put("template_id", templateId);
        param.put("page", page);
        param.put("touser", openId);
        param.put("data", data);
        param.put("miniprogram_state", miniProgramState);
        param.put("lang", "zh_CN");
        HttpEntity<String> entity = new HttpEntity<>(param.toJSONString(), headers);
        String s = restTemplate.postForObject(url, entity, String.class);
        log.info("发送订阅消息通知参数：{}", param.toString());
        log.info("发送订阅消息通知结果：{}", s);
    }

}
